import SalesPlanAPI from '../../../common/api/salesplan/salesplanmain.api.js';
import doT from '../../../vendor/template/doT.js';
import { RegExpBlock, definitionValidate } from "../../../common/validate/index.js";


(function (window, document, $) {
    // const addSalesplanTemplate = doT.template($('#add-salesplan-template').text());
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening">
<div class="toolbar-inner">
<span style='margin:0 auto;margin-top:10px'>请选择业务日期</span>
<a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a>
</div>
</div>`;
    const selectmaterial = ` <select class="weui-select" style="visibility: hidden;" v-model="item.material.id"
                                    required>
                                </select>`

    let _vm, _ownOrgs = [], _stuffInfo = [], _pickerTime, _deliveryTime, entryIndex = 1, savetype,
        indexid, custom, arrmaterial = [], entriesmaterial = [], materialparams, selectEntry = [], dataid, _entries, _entriestype = 0, saleOrgsinfo;
    $(function () {
        _vm = new Vue({
            el: "#addsalesplan-form",
            data() {
                return {
                    "saleOrg": {
                        "id": "",
                        "name": ""
                    },
                    "customer": {
                        "id": "",
                        "name": "",
                        "numCode": "",
                        "phoneNum": "",
                        "address": ""
                    },
                    "entries": [
                        {
                            "seq": "",
                            "material": {
                                "id": "",
                                "numCode": "",
                                "name": "",
                                "model": "",
                                "fassistUnit": "",
                                "baseMeasureUnit": ""
                            },
                            "fassistQty": "",
                            "baseQty": "",
                            "remark": ""
                        }
                    ],
                    "bizDate": "",
                    "deliveryDate": ""
                }
            },
            methods: {
                submit() {
                    savedata()
                },
                addSalesEntry() {
                    _addSalesEntry()

                }
            },
            // created() {
            //     if (Utils.IsNotNull(getUrlKey("id"))) {
            //         $('#salesEntry').append($('#salesEntryTem').html())
            //     }
            // },
            // mounted() {
            //     _initCommand()
            // }
        });
        _initCommand()
        _datetimePickerInit()
        _deliveryPickerInit()
        saleOrgs()
        custominfo()
        _delSalesEntry()
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化销售组织
    const saleOrgs = async () => {
        _stuffInfo = await SalesPlanAPI.getUserInfo();
        _ownOrgs = await SalesPlanAPI.postUserOrgsList();
        SalesPlanAPI.getOrgsListType().then(res => {
            let sale = res.filter(s => s.typeValue == true);
            let obj = _ownOrgs.filter(item => sale.some(item2 => item2.id == item.oId));
            let ownAccount = obj.find(s => s.oId == _stuffInfo.curOrgId);
            $('#saleOrgs').select2({
                placeholder: '请选择销售组织...', //默认文字提示
                language: "zh-CN",//汉化
                data: obj.map(item => {
                    return {
                        id: item.oId,
                        name: item.oName,
                        text: `${item.oName}`
                    }
                }),
            });
            // 编辑
            if (Utils.IsNotNull(_vm.saleOrg.id)) {
                $("#saleOrgs").val(_vm.saleOrg.id).trigger('change');
            }
            else if (Utils.IsNotNull(ownAccount)) {
                $('#saleOrgs').val(ownAccount.oId).trigger('change');
            }
            //解决字段过长
            $('#saleOrgs').on('change', function () {
                saleOrgsinfo = cutstr($('#select2-saleOrgs-container').text(), 22)
                $('#select2-saleOrgs-container').text(`${saleOrgsinfo}`)
            })
            _vm.saleOrg.id = $('#saleOrgs').select2('data')[0].id
            _vm.saleOrg.name = $('#saleOrgs').select2('data')[0].text
        })
    }
    // 初始化客户信息
    const custominfo = () => {
        SalesPlanAPI.masterCstm().then(res => {
            $('#selCustomerInfos').select2({
                placeholder: '请选择客户...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.map(item => {
                    return {
                        id: item.id,
                        name: item.name,
                        numCode: item.numCode,
                        text: `${item.name}(${item.numCode})`
                    }
                }),
            });
            if (Utils.IsNotNull(_vm.customer.id)) {
                $("#selCustomerInfos").val(_vm.customer.id).trigger('change');
                custom = cutstr($('#select2-selCustomerInfos-container').text(), 22)
                $('#select2-selCustomerInfos-container').text(`${custom}`)
            }
            else {
                $("#selCustomerInfos").val(null).trigger('change');
            }
            //解决客户字段过长
            $('#selCustomerInfos').on('change', function () {
                // cutstr(`${item.name}(${item.numCode})`, 28)
                custom = cutstr($('#select2-selCustomerInfos-container').text(), 22)
                $('#select2-selCustomerInfos-container').text(`${custom}`)
                _vm.customer.id = $('#selCustomerInfos').select2('data')[0].id
                _vm.customer.numCode = $('#selCustomerInfos').select2('data')[0].numCode
                _vm.customer.name = $('#selCustomerInfos').select2('data')[0].name
            })

        })
    }
    //业务日期控件初始化
    const _datetimePickerInit = () => {
        initCurrentDay()
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#search-date').on('click', function (e) {
            e.stopPropagation();
            $("#search-date").picker("open");
            _pickerDate();
        });
        $("#search-date").datetimePicker(
            {
                toolbarTemplate: toolbarTemplate,
                toolbarCloseText: "确定",
                toolbarCancelText: "取消",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },

                //确定选择时的操作
                onClose: function (picker) {
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
                    _pickerTime = '';
                    _pickerTime = value;
                }
            }
        );
    }
    //业务日期确认事件
    const _pickerDate = () => {
        $(document).on("click", ".close-picker", function () {
            $('#businessTime').val(_pickerTime);
            _vm.bizDate = _pickerTime
        });
    }

    // 业务日期，获取当天
    const initCurrentDay = () => {
        let todayDate = moment().format('YYYY-MM-DD')
        $('#businessTime').val(todayDate)
        _vm.bizDate = todayDate
    }

    //发货日期控件初始化
    const _deliveryPickerInit = () => {
        initCurrentDay()
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#delivery-date').on('click', function (e) {
            e.stopPropagation();
            $("#delivery-date").picker("open");
            _deliverypickerDate();
        });
        $("#delivery-date").datetimePicker(
            {
                toolbarTemplate: toolbarTemplate,
                toolbarCloseText: "确定",
                toolbarCancelText: "取消",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },
                //确定选择时的操作
                onClose: function (picker) {
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
                    _deliveryTime = '';
                    _deliveryTime = value;
                }
            }
        );
    }
    //发货日期确认事件
    const _deliverypickerDate = () => {
        $(document).on("click", ".close-picker", function () {
            $('#deliveryDate').val(_deliveryTime);
            _vm.deliveryDate = _deliveryTime
        });
    }

    //解决客户字段过长
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    // 新增分录
    const _addSalesEntry = () => {
        _entriestype = 0
        entryIndex += 1
        $('#salesEntry').append($('#salesEntryTem').html());
        $("#salesEntry").children('div').each(function (index, domele) {
            indexid = index + 1
            $(domele).attr('id', `salesEntry${indexid}`)
            $(domele).find('.entry').text(`分录${indexid}`)
            $(domele).find('.operation-button').attr('data-id', `${indexid}`)
            $(domele).find('.weui-cell__ft').empty().append(selectmaterial)
            $(domele).find('.weui-select').attr('id', `selmaterialInfos${indexid}`)
            master(`selmaterialInfos${indexid}`)
        })
        addsalesdetai()

    };
    // 增加“销售计划明细”
    const addsalesdetai = () => {
        if ($('#salesEntry div:first').find('.entrycon').find('h4').length === 0) {
            $('#salesEntry div:first').find('.entrycon').prepend(
                ` <h4 class="plantails-head" style="padding-top: 10px;padding-bottom: 10px;">计划明细</h4>`
            )
        }
    }
    // 删除分录
    const _delSalesEntry = () => {
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            delsales()
            dataid = $(this).attr('data-id')
        })

    }
    // 编辑
    const _initCommand = () => {
        if (Utils.IsNotNull(getUrlKey("id"))) {
            $("title").text("编辑销售计划");
            SalesPlanAPI.querySalesInfo(getUrlKey("id")).then(res => {
                _vm.saleOrg = res.saleOrg
                _vm.customer = res.customer
                _vm.bizDate = res.bizDate.split(' ')[0].replace(/\//g, '-')
                _vm.deliveryDate = res.deliveryDate.split(' ')[0].replace(/\//g, '-')
                _entries = res.entries

                for (let i = 0; i < res.entries.length; i++) {
                    _addSalesEntry()
                    _entriestype = 1
                }
                $('#salesEntry').find('.fassistQty').each(function (index, domele) {
                    $(domele).val(_entries[index].fassistQty)
                })
                $('#salesEntry').find('.remark').each(function (index, domele) {
                    $(domele).val(_entries[index].remark)
                })
            })
        }
    }

    // 物料
    const master = (id) => {
        SalesPlanAPI.getMaterial().then(res => {
            $(`#${id}`).select2({
                placeholder: '请选择物料...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.map(item => {
                    return {
                        id: item.id,
                        name: item.name,
                        text: `${item.name}(${item.numCode})`,
                        numCode: item.numCode,
                        model: item.model,
                        baseMeasureUnit: item.baseMeasureUnit
                    }
                }),
            });
            $(`#${id}`).on('change', function () {
                const material = cutstr($(`#select2-${id}-container`).text(), 20)
                $(`#select2-${id}-container`).text(`${material}`)
                if (Utils.IsNotNull($(`#${id}`).select2('data'))) {
                    // 渲染规格和基本计量单位
                    let _materinfo = $(this).parents('.materialinfo').siblings('div')
                    _materinfo.find(`.material-model`).val($(`#${id}`).select2('data')[0].model)
                    _materinfo.find(`.material-baseMeasureUnit`).val($(`#${id}`).select2('data')[0].baseMeasureUnit)
                }
                // 选择
                arrmaterial[masterind] = ($(`#${id}`).select2('data')[0])
            })
            $(`#${id}`).siblings('span').on('click', function () {
                $('.select2-container').children('span').addClass('materialinfo-select')
            })
            let masterind = id.substr(id.length - 1, 1) - 1
            if (Utils.IsNotNull(_entriestype)) {
                $(`#${id}`).val(_entries[masterind].material.id).trigger('change');
                $(`#${id}`).change()
            }
            else if (!Utils.IsNotNull(arrmaterial[masterind])) {
                $(`#${id}`).val(null).trigger('change');
            }
            else {
                $(`#${id}`).val(arrmaterial[masterind].id).trigger('change');
                $(`#${id}`).change()
            }
        })

    }

    // 保存
    const savedata = () => {
        if (!Utils.IsNotNull($('#salesEntry').text())) {
            return $.toptip(`请添加计划明细!`, 'warning');
        }
        if (!Utils.IsNotNull($('#deliveryDate').val())) {
            return $.toptip(`请选择发货日期!`, 'warning');
        }
        if (!Utils.IsNotNull($('#selCustomerInfos').select2('data'))) {
            return $.toptip(`请选择客户!`, 'warning');
        }
        if (!_vm.customer.phoneNum) { return $.toptip('请输入联系方式', 'warning') } else {
            if (!/^1[3456789]\d{9}$/.test(_vm.customer.phoneNum.trim())) {
                return $.toptip('请输入正确的联系方式', 'warning');
            }
        };
        if (!Utils.IsNotNull($(`#selmaterialInfos${indexid}`).select2('data'))) {
            return $.toptip(`请选择物料!`, 'warning');
        }
        $("#salesEntry").children('div').each(function (index, domele) {
            if (!Utils.IsNotNull($(domele).find('.fassistQty').val())) {
                return $.toptip(`请输入计划辅助数量!`, 'warning');
            }

            indexid = index + 1
            materialparams = {
                "seq": indexid,
                "material": {
                    "id": $(`#selmaterialInfos${indexid}`).select2('data')[0].id,
                    "numCode": $(`#selmaterialInfos${indexid}`).select2('data')[0].numCode,
                    "name": $(`#selmaterialInfos${indexid}`).select2('data')[0].name,
                    "model": $(`#selmaterialInfos${indexid}`).select2('data')[0].model,
                    // "fassistUnit": "",
                    "baseMeasureUnit": $(`#selmaterialInfos${indexid}`).select2('data')[0].baseMeasureUnit
                },
                "fassistQty": $(domele).find('.fassistQty').val(),
                // "baseQty": "",
                "remark": $(domele).find('.remark').val()
            }
            // "deliveryDate": ""
            entriesmaterial[index] = materialparams

        })
        let cs = $("#salesEntry").find('.fassistQty').length
        // 解决验证之后再弹出提示框
        $("#salesEntry").find('.fassistQty').each(function (index, domele) {
            // selectEntry = true
            if (!Utils.IsNotNull($(domele).val())) {
                selectEntry[index] = 0
            }
            else {
                selectEntry[index] = 1
            }

        })
        let flag = selectEntry.some(function (value, index, array) {
            return value === 0;
        })
        if (flag === false) {
            submitsales()
        }

    }
    // 保存提示
    const submitsales = () => {
        if (Utils.IsNotNull(getUrlKey("id"))) {
            savetype = '修改'
        }
        else {
            savetype = '保存'
        }
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认${savetype}该单据并提交？</div>
					</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        if (Utils.IsNotNull(entriesmaterial)) {
                            let _param = { ...{ entries: entriesmaterial }, ...{ saleOrg: _vm.saleOrg }, ...{ customer: _vm.customer }, bizDate: _vm.bizDate, deliveryDate: _vm.deliveryDate };
                            if (Utils.IsNotNull(getUrlKey("id"))) {
                                SalesPlanAPI.ediSalesList(getUrlKey("id"), _param).then(res => {
                                    $.toptip('请求成功。', 'success');
                                    $.closeModal();
                                    location.href = `./salesplanmain.html?v=${Utils.GetTime()}`;
                                })
                            }
                            else {
                                SalesPlanAPI.addSalesList(_param).then(res => {
                                    $.toptip('请求成功。', 'success');
                                    $.closeModal();
                                    location.href = `./salesplanmain.html?v=${Utils.GetTime()}`;
                                })
                            }
                        }
                    }
                }
            ]
        });
    }
    // 删除提示
    const delsales = () => {
        $.modal({
            autoClose: false,
            title: '删除提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该单据？</div>
					</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "确定", onClick: function () {
                        _entriestype = 0
                        $(`div[data-id = ${dataid}]`).parents(`#salesEntry${dataid}`).remove()
                        $("#salesEntry").children('div').each(function (index, domele) {
                            indexid = index + 1
                            $(domele).attr('id', `salesEntry${indexid}`)
                            $(domele).find('.entry').text(`分录${indexid}`)
                            $(domele).find('.operation-button').attr('data-id', `${indexid}`)
                            $(domele).find('.weui-cell__ft').empty().append(selectmaterial)
                            $(domele).find('.weui-select').attr('id', `selmaterialInfos${indexid}`)
                            master(`selmaterialInfos${indexid}`)
                        })
                        arrmaterial.splice(dataid - 1, 1);
                        entriesmaterial.splice(dataid - 1, 1);
                        addsalesdetai()
                        $.closeModal();
                    }
                }
            ]
        });
    }
    //取消按钮，返回列表
    $(document).on('click', '#returnMain', function () {
        location.href = `../salesplan/salesplanmain.html?v=${Utils.GetTime()}`;
    });


    /** 获取地址栏的 参数  传入 字段返回值 */
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
})(window, document, jQuery)